import React, { useState, useEffect } from 'react';
import { Card, Typography, Row, Col, Form, Select, Input, Button, Table, Tabs, Tag, Spin, Divider, List, Progress, message } from 'antd';
import { BookOutlined, BarChartOutlined, BulbOutlined, UserOutlined, CheckCircleOutlined } from '@ant-design/icons';
import axios from 'axios'; // 引入axios进行HTTP请求
import './index.css';
import { fetchColleges, fetchMajors, submitPlanningAnalysis } from './api';

const { Title, Paragraph, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

/**
 * 升学规划 - 新界面
 */
function FurtherEducationPlanning() {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [studentInfo, setStudentInfo] = useState(null);
  const [collegeOptions, setCollegeOptions] = useState([]);
  const [majorOptions, setMajorOptions] = useState([]);
  const [filteredMajorOptions, setFilteredMajorOptions] = useState([]);
  const [selectedColleges, setSelectedColleges] = useState([]);
  const [selectedMajors, setSelectedMajors] = useState([]);
  const [interestText, setInterestText] = useState('');
  const [planningResults, setPlanningResults] = useState(null);
  const [activeTab, setActiveTab] = useState('1');
  const [isDataLoading, setIsDataLoading] = useState(false);
  const [selectedCollege, setSelectedCollege] = useState(null);
  const [selectedMajor, setSelectedMajor] = useState(null);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [analysisResult, setAnalysisResult] = useState(null);
  
  // 模拟学生信息
  useEffect(() => {
    fetchStudentInfo();
    fetchCollegesAndMajors();
  }, []);
  
  // 监听所选院校变化，更新专业选项
  useEffect(() => {
    filterMajorOptions();
  }, [selectedColleges, majorOptions]);
  
  // 根据所选院校筛选专业选项
  const filterMajorOptions = () => {
    if (selectedColleges.length === 0) {
      // 如果没有选择院校，显示所有专业
      setFilteredMajorOptions(majorOptions);
    } else {
      // 如果选择了院校，只显示对应院校的专业
      const filtered = majorOptions.filter(major => {
        // 检查专业的collegeNo或college字段是否在所选院校中
        return selectedColleges.includes(major.collegeNo) || 
               selectedColleges.includes(major.college);
      });
      
      console.log('筛选后的专业:', filtered, '所选院校:', selectedColleges);
      setFilteredMajorOptions(filtered);
      
      // 如果筛选后没有专业，显示提示
      if (filtered.length === 0 && majorOptions.length > 0) {
        message.info('当前所选院校下没有找到匹配的专业');
      }
    }
  };
  
  // 获取学生信息
  const fetchStudentInfo = async () => {
    try {
      setIsDataLoading(true);
      // 真实API调用
      // const response = await axios.get('/api/student/profile');
      // setStudentInfo(response.data);
      
      // 临时使用模拟数据，实际开发中替换为上面的API调用
      setTimeout(() => {
        setStudentInfo({
          name: '李明',
          studentId: 'S20230102',
          grade: '高三（1）班',
          score: 645,
          rank: 1230,
          subjects: {
            '语文': 120,
            '数学': 138,
            '英语': 132,
            '物理': 89,
            '化学': 86,
            '生物': 80
          }
        });
        setIsDataLoading(false);
      }, 500);
    } catch (error) {
      console.error('获取学生信息失败:', error);
      message.error('获取学生信息失败，请稍后重试');
      setIsDataLoading(false);
    }
  };
  
  // 获取院校和专业数据
  const fetchCollegesAndMajors = async () => {
    try {
      setIsDataLoading(true);
      
      // 调用API获取院校列表
      const colleges = await fetchColleges();
      console.log('成功获取院校数据:', colleges);
      
      if (colleges && colleges.length > 0) {
        setCollegeOptions(colleges);
      } else {
        message.warning('未获取到院校数据，请刷新页面重试');
      }
      
      setIsDataLoading(false);
    } catch (error) {
      console.error('获取院校和专业数据失败:', error);
      message.error('获取院校和专业数据失败，请稍后重试');
      setIsDataLoading(false);
    }
  };
  
  // 根据院校ID获取该院校的专业
  const fetchMajorsByCollege = async (collegeId) => {
    try {
      setIsDataLoading(true);
      // 调用API获取专业
      const majors = await fetchMajors(collegeId);
      console.log(`成功获取院校(${collegeId})的专业数据:`, majors);
      
      if (!majors || majors.length === 0) {
        message.info(`未找到该院校的专业数据`);
      }
      
      setIsDataLoading(false);
      return majors;
    } catch (error) {
      console.error(`获取院校${collegeId}的专业失败:`, error);
      message.error('获取专业数据失败，请稍后重试');
      setIsDataLoading(false);
      return [];
    }
  };
  
  // 处理院校选择变化
  const handleCollegeChange = async (values) => {
    console.log('选择的院校:', values);
    setSelectedColleges(values);
    
    // 清除已选专业
    setSelectedMajors([]);
    
    // 当选择了新的院校时，调用API获取该院校的专业列表
    if (values && values.length > 0) {
      try {
        // 获取每个所选院校的专业
        const majorsPromises = values.map(collegeId => fetchMajorsByCollege(collegeId));
        const majorsByColleges = await Promise.all(majorsPromises);
        
        // 合并所有院校的专业
        const allMajors = [].concat(...majorsByColleges);
        console.log('合并后的专业列表:', allMajors);
        
        // 更新专业选项
        setMajorOptions(allMajors);
        setFilteredMajorOptions(allMajors);
      } catch (error) {
        console.error('获取专业数据失败:', error);
      }
    } else {
      // 没有选择院校时，清空专业列表
      setFilteredMajorOptions([]);
      setMajorOptions([]);
    }
  };
  
  // 处理专业选择变化
  const handleMajorChange = (values) => {
    setSelectedMajors(values);
  };
  
  // 处理个人特长与兴趣输入变化
  const handleInterestChange = (e) => {
    setInterestText(e.target.value);
  };
  
  // 生成升学规划
  const generatePlanning = async () => {
    // 表单验证
    if (selectedColleges.length === 0) {
      message.warning('请至少选择一所意向院校');
      return;
    }
    
    if (selectedMajors.length === 0) {
      message.warning('请至少选择一个专业');
      return;
    }
    
    setLoading(true);
    
    try {
      // 构建分析请求数据
      const analysisData = {
        collegeNo: selectedColleges[0], // API当前只支持单个院校分析
        professionNo: selectedMajors[0], // API当前只支持单个专业分析
        interestDescription: interestText, // 兴趣描述
        studentId: studentInfo?.studentId || '',
        studentName: studentInfo?.name || '',
        // 如果支持多选，可以添加这些字段
        collegeList: selectedColleges,
        professionList: selectedMajors,
        // 可以添加更多学生相关信息
      };
      
      // 调用API提交规划分析请求
      const result = await submitPlanningAnalysis(analysisData);
      setPlanningResults(result);
      setActiveTab('2'); // 切换到规划结果选项卡
      
      setLoading(false);
      
      message.success('升学规划生成成功！');
    } catch (error) {
      console.error('生成升学规划失败:', error);
      message.error('生成规划失败，请稍后重试');
      setLoading(false);
    }
  };
  
  // 根据专业获取相关职业
  const getCareersForMajor = (majorName) => {
    const careerMap = {
      '计算机科学与技术': ['软件工程师', '算法工程师', '技术架构师'],
      '软件工程': ['软件开发工程师', '测试工程师', '项目经理'],
      '人工智能': ['AI研究员', '机器学习工程师', '数据科学家'],
      '电子信息工程': ['电子设计工程师', '通信工程师', '硬件开发工程师'],
      '数据科学与大数据技术': ['数据分析师', '大数据工程师', '商业智能专家'],
      '临床医学': ['临床医生', '医学研究员', '健康管理师'],
      '金融学': ['金融分析师', '投资顾问', '风险控制师'],
      '法学': ['律师', '法律顾问', '司法人员']
    };
    
    return careerMap[majorName] || ['行业专家', '研究人员', '教育工作者'];
  };
  
  // 获取专业优势匹配分析
  const getStrengthsMatch = (majorName, studentInfo) => {
    // 根据专业和学生信息生成匹配分析
    if (majorName.includes('计算机') || majorName.includes('软件') || majorName.includes('人工智能')) {
      return '数学基础扎实，逻辑思维能力强，对技术领域有浓厚兴趣。';
    } else if (majorName.includes('电子') || majorName.includes('数据')) {
      return '数学和物理成绩优秀，具有良好的分析能力，适合从事技术研究工作。';
    } else if (majorName.includes('医学')) {
      return '生物和化学基础较好，具有耐心和责任心，适合医学相关专业。';
    } else if (majorName.includes('金融')) {
      return '数学能力强，分析问题深入，对经济金融领域有一定了解。';
    } else if (majorName.includes('法学')) {
      return '语文和英语表达能力优秀，逻辑思维清晰，善于分析和解决问题。';
    }
    
    return '学科基础扎实，综合素质良好，适合该专业的学习和发展。';
  };
  
  // 获取专业弱项分析
  const getWeaknessesMatch = (majorName) => {
    if (majorName.includes('计算机') || majorName.includes('软件') || majorName.includes('人工智能')) {
      return '可能需要加强英语表达和团队合作能力，建议多参与项目实践。';
    } else if (majorName.includes('电子') || majorName.includes('数据')) {
      return '可能需要提升创新思维和工程实践能力，建议参与相关竞赛和项目。';
    } else if (majorName.includes('医学')) {
      return '医学专业学习时间长，压力大，需要有足够的心理准备和持久的学习动力。';
    } else if (majorName.includes('金融')) {
      return '金融领域变化快，需要加强实时市场分析能力和风险意识。';
    } else if (majorName.includes('法学')) {
      return '法学专业需要大量记忆和理解，建议加强专业词汇的积累和案例分析能力。';
    }
    
    return '可能需要加强专业方向的针对性学习，建议提前了解相关领域知识。';
  };
  
  // 渲染学生信息卡片
  const renderStudentInfoCard = () => {
    if (!studentInfo) return <Spin />;
    
    return (
      <Card title="学生基本信息" className="info-card">
        <Row gutter={[16, 16]}>
          <Col span={8}>
            <div className="student-basic-info">
              <div className="info-item">
                <Text strong>姓名：</Text>
                <Text>{studentInfo.name}</Text>
              </div>
              <div className="info-item">
                <Text strong>学号：</Text>
                <Text>{studentInfo.studentId}</Text>
              </div>
              <div className="info-item">
                <Text strong>班级：</Text>
                <Text>{studentInfo.grade}</Text>
              </div>
              <div className="info-item">
                <Text strong>总分：</Text>
                <Text>{studentInfo.score}</Text>
              </div>
              <div className="info-item">
                <Text strong>排名：</Text>
                <Text>{studentInfo.rank}</Text>
              </div>
            </div>
          </Col>
          <Col span={16}>
            <div className="student-subjects">
              <Title level={5}>各科成绩</Title>
              <Row gutter={[16, 16]}>
                {Object.entries(studentInfo.subjects).map(([subject, score]) => (
                  <Col span={8} key={subject}>
                    <Card size="small" className="subject-card">
                      <div className="subject-name">{subject}</div>
                      <div className="subject-score">{score}</div>
                    </Card>
                  </Col>
                ))}
              </Row>
            </div>
          </Col>
        </Row>
      </Card>
    );
  };
  
  // 渲染目标选择表单
  const renderTargetSelectionForm = () => {
    return (
      <Card title="目标院校与专业选择" className="target-selection-card">
        <Form layout="vertical">
          <Form.Item 
            label="意向院校选择（可多选）" 
            required
            tooltip="请至少选择一所院校"
          >
            <Select
              mode="multiple"
              placeholder="请选择意向院校"
              style={{ width: '100%' }}
              value={selectedColleges}
              onChange={handleCollegeChange}
              optionFilterProp="label"
              showSearch
              allowClear
              loading={isDataLoading}
              notFoundContent={isDataLoading ? <Spin size="small" /> : (collegeOptions.length === 0 ? "暂无数据，请刷新页面" : "没有找到匹配的院校")}
            >
              {collegeOptions.map(college => (
                <Option key={college.value} value={college.value} label={college.label}>
                  <div className="college-option">
                    <span>{college.label}</span>
                    <span className="college-tags">
                      {college.tier && <Tag color="blue">{college.tier}</Tag>}
                      {college.location && <Tag color="green">{college.location}</Tag>}
                    </span>
                  </div>
                </Option>
              ))}
            </Select>
            {collegeOptions.length === 0 && !isDataLoading && (
              <div style={{ marginTop: 8, color: '#ff4d4f' }}>
                系统未能加载院校数据，请刷新页面或联系管理员
              </div>
            )}
          </Form.Item>
          
          <Form.Item 
            label="专业倾向（可多选）"
            tooltip={selectedColleges.length === 0 ? "选择院校后可以筛选出对应院校的专业" : ""}
          >
            <Select
              mode="multiple"
              placeholder={selectedColleges.length > 0 ? "请选择专业倾向" : "请先选择意向院校"}
              style={{ width: '100%' }}
              value={selectedMajors}
              onChange={handleMajorChange}
              optionFilterProp="label"
              showSearch
              allowClear
              loading={isDataLoading}
              disabled={selectedColleges.length === 0}
              notFoundContent={
                isDataLoading ? <Spin size="small" /> : 
                (selectedColleges.length === 0 ? "请先选择意向院校" : 
                 filteredMajorOptions.length === 0 ? "没有找到对应院校的专业" : "没有找到匹配的专业")
              }
            >
              {filteredMajorOptions.map(major => (
                <Option key={major.value} value={major.value} label={major.label}>
                  <div className="major-option">
                    <span>{major.label}</span>
                    {major.category && <Tag color="purple">{major.category}</Tag>}
                    <small style={{ color: '#999' }}>
                      {collegeOptions.find(c => c.value === (major.collegeNo || major.college))?.label || ''}
                    </small>
                  </div>
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item label="个人特长与兴趣">
            <Input.TextArea 
              rows={4} 
              placeholder="请描述您的特长、兴趣爱好和职业理想等" 
              value={interestText}
              onChange={handleInterestChange}
            />
          </Form.Item>
          
          <Form.Item>
            <Button 
              type="primary" 
              onClick={generatePlanning} 
              loading={loading}
              icon={<BarChartOutlined />}
              size="large"
              block
              disabled={selectedColleges.length === 0 || selectedMajors.length === 0}
            >
              生成升学规划分析
            </Button>
          </Form.Item>
        </Form>
      </Card>
    );
  };
  
  // 渲染规划结果
  const renderPlanningResults = () => {
    if (!planningResults) {
      return (
        <div className="no-results">
          <BookOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
          <Paragraph style={{ marginTop: 16 }}>
            请在左侧选择目标院校和专业，然后点击"生成升学规划分析"按钮
          </Paragraph>
        </div>
      );
    }
    
    return (
      <Tabs activeKey={activeTab} onChange={setActiveTab} className="result-tabs">
        <TabPane tab="院校录取分析" key="2">
          <div className="college-analysis">
            {planningResults.collegeAnalysis.map((college) => (
              <Card key={college.collegeId} className="college-card" title={college.collegeName}>
                <div className="probability-section">
                  <div className="probability-label">录取概率</div>
                  <Progress 
                    type="circle" 
                    percent={college.admissionProbability} 
                    width={80}
                    format={percent => `${percent}%`}
                    status={college.admissionProbability > 80 ? "success" : "normal"}
                  />
                </div>
                
                <Divider />
                
                <div className="college-detail-section">
                  <div className="detail-item">
                    <Title level={5}>历年录取情况</Title>
                    <Table 
                      dataSource={college.admissionHistory} 
                      pagination={false}
                      size="small"
                      rowKey="year"
                      columns={[
                        { title: '年份', dataIndex: 'year', key: 'year' },
                        { title: '最低分', dataIndex: 'lowestScore', key: 'score' },
                        { title: '最低位次', dataIndex: 'lowestRank', key: 'rank' }
                      ]}
                    />
                  </div>
                  
                  <div className="detail-item">
                    <Title level={5}>推荐专业</Title>
                    <div className="recommended-majors">
                      {college.recommendedMajors.map((major, index) => (
                        <Tag key={index} color="blue">{major}</Tag>
                      ))}
                    </div>
                  </div>
                  
                  <div className="detail-item">
                    <Title level={5}>匹配分析</Title>
                    <Paragraph>{college.strengthAnalysis}</Paragraph>
                  </div>
                  
                  <div className="detail-item">
                    <Title level={5}>升学建议</Title>
                    <Paragraph><CheckCircleOutlined style={{ color: '#52c41a' }} /> {college.suggestion}</Paragraph>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabPane>
        
        <TabPane tab="专业匹配分析" key="3">
          <div className="major-analysis">
            {planningResults.majorAnalysis.map((major) => (
              <Card key={major.majorId} className="major-card" title={major.majorName}>
                <div className="match-score-section">
                  <Progress 
                    type="dashboard" 
                    percent={major.matchScore} 
                    width={80}
                    format={percent => `${percent}%`}
                  />
                  <span className="match-label">匹配度</span>
                </div>
                
                <Divider />
                
                <div className="major-detail-section">
                  <div className="detail-item">
                    <Title level={5}>学科适配度</Title>
                    <Row gutter={[16, 16]}>
                      {Object.entries(major.subjectFit).map(([subject, score]) => (
                        <Col span={8} key={subject}>
                          <div className="subject-fit">
                            <span>{subject}</span>
                            <Progress percent={score} size="small" />
                          </div>
                        </Col>
                      ))}
                    </Row>
                  </div>
                  
                  <div className="detail-item">
                    <Title level={5}>就业前景</Title>
                    <div className="career-prospects">
                      {major.careerProspects.map((career, index) => (
                        <Tag key={index} color="purple">{career}</Tag>
                      ))}
                    </div>
                  </div>
                  
                  <div className="detail-item">
                    <Title level={5}>优势匹配</Title>
                    <Paragraph>{major.strengthsMatch}</Paragraph>
                  </div>
                  
                  <div className="detail-item">
                    <Title level={5}>待提升项</Title>
                    <Paragraph>{major.weaknessesMatch}</Paragraph>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </TabPane>
        
        <TabPane tab="学习路径规划" key="4">
          <Card className="learning-path-card">
            <Title level={4}>升学路径规划</Title>
            <Paragraph className="path-intro">
              基于您的学术表现和目标选择，我们为您定制了以下学习路径规划，以帮助您有序地实现升学目标。
            </Paragraph>
            
            <div className="path-timeline">
              {planningResults.learningPath.map((stage, index) => (
                <div key={index} className="path-stage">
                  <div className="stage-header">
                    <div className="stage-marker">{index + 1}</div>
                    <div className="stage-title">
                      <Title level={5}>{stage.stage}</Title>
                      <Tag color="blue">{stage.duration}</Tag>
                    </div>
                  </div>
                  
                  <div className="stage-content">
                    <Paragraph>{stage.focus}</Paragraph>
                    <div className="stage-key-points">
                      <Title level={5}>关键行动点：</Title>
                      <ul>
                        {stage.key.map((item, i) => (
                          <li key={i}>{item}</li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            
            <div className="path-summary">
              <Title level={5}><BulbOutlined /> 总体建议</Title>
              <Paragraph>
                根据您的学习情况和目标，建议您在保持数学和物理等优势学科的同时，适当提升英语和化学成绩。
                在备考阶段，建议每周制定详细的学习计划，并定期自我评估进度。大学阶段应该积极参与专业相关
                的实践活动和科研项目，为未来职业发展打下坚实基础。
              </Paragraph>
            </div>
          </Card>
        </TabPane>
      </Tabs>
    );
  };

  // 提交升学规划分析请求
  const handleSubmitAnalysis = async (formData) => {
    if (!selectedCollege || !selectedMajor) {
      message.error('请选择院校和专业');
      return;
    }
    
    setSubmitLoading(true);
    try {
      // 构建提交的数据，结合表单数据和选择的院校专业
      const data = {
        ...formData,
        collegeNo: selectedCollege.value,
        collegeName: selectedCollege.label,
        professionNo: selectedMajor.value,
        professionName: selectedMajor.label
      };
      
      const result = await submitPlanningAnalysis(data);
      setAnalysisResult(result.data);
      message.success('分析请求提交成功');
    } catch (error) {
      console.error('提交分析请求失败', error);
      message.error('提交失败，请稍后重试');
    } finally {
      setSubmitLoading(false);
    }
  };

  return (
    <div className="further-education-planning-container">
      <Title level={2} style={{ marginBottom: '20px' }}>升学规划</Title>
      
      <Row gutter={[24, 24]}>
        <Col span={24}>
          {renderStudentInfoCard()}
        </Col>
        
        <Col span={8}>
          {renderTargetSelectionForm()}
        </Col>
        
        <Col span={16}>
          {renderPlanningResults()}
        </Col>
      </Row>
    </div>
  );
}

export default FurtherEducationPlanning; 